var DomListener = {
    init: function () {
        this.bind_expand_panel()
        this.bind_reset_button()
        // this.bind_form_validate()
        this.set_ajax_header()
        this.form_change_per_page()
        // 在app.js，helper初始化
        // this.autoBindDateTimePicker()
        this.bind_select2()
        this.back_to_tab_on_loaded()
        // this.move_bottom_paginator_to_table()
    },
    back_to_tab_on_loaded: function () {
        // 从tab页切换刷新，返回页面的时候自动切换只之前的tab页
        $('.nav-tabs[data-toggle="tabs"] a').on('click', function () {
            current_tab = $(this).attr('href')
        })
        if (current_tab != null && $(current_tab).length > 0) {
            $('.nav-tabs[data-toggle="tabs"] a[href="' + current_tab + '"]').click()
        }
    },

    // 通过点击panel里面的+/-，展开收起panel-body
    bind_expand_panel: function () {
        $(document).undelegate('i.expand-panel-body', 'click').delegate('i.expand-panel-body', 'click', function () {
            if ($(this).hasClass('fa-minus-square-o')) {
                $(this).removeClass('fa-minus-square-o').addClass('fa-plus-square-o').parents('.panel:first').find('.panel-body').addClass('hide')
            } else {
                $(this).removeClass('fa-plus-square-o').addClass('fa-minus-square-o').parents('.panel:first').find('.panel-body').removeClass('hide')
            }
        })
    },

    // 绑定modal弹框ajax加载的datepicker
    // 不用在init方法里加上此方法，因为在app.js里面已经初始化过一遍
    // 在input里格式化结果 --> data: {'date-format': 'Y-M-D H:m'}
    bind_modal_datetimepicker: function () {
        $('.application-modal .js-datetimepicker').each(function () {
            var $input = $(this)
            $input.datetimepicker({
                format: $input.data('format') ? $input.data('format') : false,
                useCurrent: $input.data('use-current') ? $input.data('use-current') : false,
                locale: moment.locale('' + ($input.data('locale') ? $input.data('locale') : '') + ''),
                showTodayButton: $input.data('show-today-button') ? $input.data('show-today-button') : false,
                showClear: $input.data('show-clear') ? $input.data('show-clear') : false,
                showClose: $input.data('show-close') ? $input.data('show-close') : false,
                sideBySide: $input.data('side-by-side') ? $input.data('side-by-side') : false,
                inline: $input.data('inline') ? $input.data('inline') : false,
                icons: {
                    time: 'si si-clock',
                    date: 'si si-calendar',
                    up: 'si si-arrow-up',
                    down: 'si si-arrow-down',
                    previous: 'si si-arrow-left',
                    next: 'si si-arrow-right',
                    today: 'si si-size-actual',
                    clear: 'si si-trash',
                    close: 'si si-close'
                }
            });
        })

    },

    // 修复css-checkbox点击问题
    // bind_modal_css_checkbox: function () {
    //   $('#application-modal .css-checkbox').unbind().click(function () {
    //     $(this).find('input:checkbox').click()
    //   })
    //   // $('#application-modal .css-checkbox>input:checkbox')
    // },

    bind_reset_button: function () {
        $("a[type=reset]").click(function () {
            $(this).parents('form:first').find(':input').not(':button, :submit, :reset, :hidden').val('');
            return false;
        });
    },

    bind_form_validate: function () {
        $('body').delegate('.form-validate [type=submit], btn-validate ', 'click', function () {
            $('.has-error').removeClass('has-error');
            $('.validate-error-message').remove();
            var err = 0;
            $(this).parents('form').first().find('input:visible, select:visible , textarea').each(function () {
                if ($.trim($(this).val()) == '' && $(this).attr('validate') != 'skip') {
                    err += 1;
                    $(this).parent().addClass('has-error');
                    // setTimeout(function () {
                    //     $('.has-error').removeClass('has-error');
                    // }, 2500)
                }
            });
            if (err > 0) {
                return false
            }
        });
    },


    set_ajax_header: function () {
        // Ajax提交表单的时候加上token，防止 InvalidAuthenticityToken 报错
        $.ajaxSetup({
            beforeSend: function (xhr) {
                xhr.setRequestHeader("X-CSRF-Token", $("meta[name=\"csrf-token\"]").attr("content"));
            }
        })
    },
    // 绑定日期时间选择器
    autoBindDateTimePicker: function () {
        // data: {'date-format': 'Y-M-D H:m'}
        $.datepicker.regional["zh-CN"] = {
            closeText: "关闭",
            prevText: "<",
            nextText: ">",
            currentText: "今天",
            monthNames: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
            monthNamesShort: ["一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "十二"],
            dayNames: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"],
            dayNamesShort: ["周日", "周一", "周二", "周三", "周四", "周五", "周六"],
            dayNamesMin: ["日", "一", "二", "三", "四", "五", "六"],
            weekHeader: "周",
            dateFormat: "yy-mm-dd",
            firstDay: 1,
            isRTL: !1,
            showMonthAfterYear: !0,
            yearSuffix: "年"
        };
        $('.date-time-picker').datetimepicker({
            autoclose: true,
            timeOnlyTitle: '选择时间',
            timeText: '时间',
            hourText: '小时',
            minuteText: '分钟',
            secondText: '秒钟',
            millisecText: '微秒',
            timezoneText: '时区',
            currentText: '现在时间',
            closeText: '关闭',
            dateFormat: 'yy-mm-dd',
            timeFormat: 'HH:mm:ss',
            amNames: ['AM', 'A'],
            pmNames: ['PM', 'P'],
            isRTL: false
        })
    },


    // datepicker_default: function () {
    //   $.datepicker.regional["zh-CN"] = {
    //     closeText: "关闭",
    //     prevText: "<",
    //     nextText: ">",
    //     currentText: "今天",
    //     monthNames: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
    //     monthNamesShort: ["一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "十二"],
    //     dayNames: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"],
    //     dayNamesShort: ["周日", "周一", "周二", "周三", "周四", "周五", "周六"],
    //     dayNamesMin: ["日", "一", "二", "三", "四", "五", "六"],
    //     weekHeader: "周",
    //     dateFormat: "yy-mm-dd",
    //     firstDay: 1,
    //     isRTL: !1,
    //     showMonthAfterYear: !0,
    //     yearSuffix: "年"
    //   };
    //   $.datepicker.setDefaults($.datepicker.regional["zh-CN"]);
    //   // 点出去或者选择了时间以后就自动隐藏，格式化时间为 年-月-日
    //   $('.date-picker').datepicker({autoclose: true, dateFormat: 'yy-mm-dd'});
    //   // 搜索表单后填充的内容，自动去掉日期后面的时间
    //   $.each($('input.date-picker'), function () {
    //     $(this).val($(this).val().split(' ')[0])
    //   })
    // },

    form_change_per_page: function () {
        // 切换每页数量提交表单
        $('.per_page_num_selector').on('change', function () {
            if ($('#per_page').length > 0) {
                $('#per_page').val($(this).val())
                $('#per_page').parents('form:first').submit()
            }
        })
        // input框跳转至指定页
        $('.pagination_go_page').on('change', function () {
            var obj = $(this).siblings('span.go_page').find('a').first()
            if ($(this).val() <= 0 || $(this).val() > $(this).data('max-page')) {
                alert(current_locales['page_enter_error'])
                return false
            }
            if (obj.length > 0) {
                // 借用上一页、下一页的链接，替换page=xx以实现翻页
                Turbolinks.visit(obj.attr('href')
                    .replace(/\?page=[0-9]+/, '?page=' + $(this).val())
                    .replace(/&page=[0-9]+/, '&page=' + $(this).val()))
            }
        })
    },
    bind_select2: function (obj) {
        // 解决modal的输入框无法focus的问题
        $.fn.modal.Constructor.prototype.enforceFocus = $.noop;
        // 默认读取placeholder属性内容或者第一个option内容作为显示
        $.each($(obj || '.js-select2'), function () {
            var placeholder = $(this).attr('placeholder'),
                option = {language: "zh-CN"};
            if (is_blank(placeholder))
                option.default_text = this.options.length > 0 ? this.options[0].innerHTML : '请选择'
            else
                option.default_text = placeholder
            // // 解决jQueryUI的dialog内不能focus问题 https://github.com/select2/select2/issues/5062
            // if ($(this).parents('.ui-dialog:first').length > 0)
            //   option.dropdownParent = $(this).parents('.ui-dialog:first')
            $(this).select2(option)
        })
    },
    move_bottom_paginator_to_table: function (target_table_selector) {
        // 废弃
        target_table_selector = target_table_selector || 'table.index-data-table'
        if ($('.bottom-pagination').length > 0 && !$('.bottom-pagination').parent().hasClass('td-bottom-pagination') && $(target_table_selector).length > 0) {
            var cols = $(target_table_selector + '>thead>tr:first th').length
            if (cols > 0) {
                $(target_table_selector + '>tbody').append("<tr><td class='td-bottom-pagination' colspan='" + cols + "'></td></tr>")
                $('.bottom-pagination').appendTo(target_table_selector + ' td.td-bottom-pagination')
            }
        }
    }
}
